const fs = require('fs');
const os = require('os');
const path = require('path');

// 目标内容，前后各空一行
const newLines = [
  '',
  'electron-mirror=https://registry.npmmirror.com/-/binary/electron/',
  'electron_custom_dir={{ version }}',
  ''
];

// 解析平台
const platform = os.platform();
const username = os.userInfo().username;

let npmrcPath;

if (platform === 'win32') {
  // Windows: 通常位于 C:\Users\用户名\.npmrc
  const userHome = process.env.USERPROFILE || `C:\\Users\\${username}`;
  npmrcPath = path.join(userHome, '.npmrc');
} else {
  // macOS/Linux
  npmrcPath = path.join(os.homedir(), '.npmrc');
}

console.log(`正在修改 ${npmrcPath} ...`);

// 读取现有 .npmrc 内容（如果存在）
let originalContent = '';
if (fs.existsSync(npmrcPath)) {
  originalContent = fs.readFileSync(npmrcPath, 'utf8');
}

// 检查是否已经存在目标内容的核心行，避免重复添加
const coreLines = [
  'electron-mirror=https://registry.npmmirror.com/-/binary/electron/',
  'electron_custom_dir={{ version }}'
];

let needAdd = coreLines.some(line => !originalContent.includes(line));

if (needAdd) {
  // 确保原内容以换行结尾
  if (!originalContent.endsWith('\n')) {
    originalContent += '\n';
  }

  // 拼接新内容（带前后空行）
  originalContent += newLines.join('\n');

  // 确保文件末尾也有换行
  if (!originalContent.endsWith('\n')) {
    originalContent += '\n';
  }

  fs.writeFileSync(npmrcPath, originalContent, 'utf8');
  console.log('✅ .npmrc 文件已更新（带前后空行）。');
} else {
  console.log('ℹ️ .npmrc 文件已包含所有内容，无需更新。');
}